<template>
    <div class="shopcart-container">
        <div v-if="cartList.length>0">
            <!-- 商品列表区域 -->
            <van-row v-for="(item, i) in cartList" :key="i" type="flex" align="center">
                <van-col span="1" align="center" >
                    <!-- 复选框 -->
                    <div class="checkbox">
                        <input
                            type="checkbox"
                            v-model="item.is_checked"
                            @change="onCheckedChange(item)"
                            :disabled="item.goods_num == 0"
                        />
                    </div>
                </van-col>
                <van-col span="5">
                    <!-- 中间商品图片 -->
                    <van-icon
                        size="80"
                        :name="APIDomainName + item.goods_img"
                    ></van-icon>
                </van-col>
                <van-col span="18">
                    <van-row class="info van-multi-ellipsis--l3">{{ item.goods_name }}</van-row>
                    <van-row gutter="40" type="flex" align="center">
                        <van-col span="8" class="price">¥{{ item.price }}</van-col>
                        <van-col span="16" class="opration">
                            <van-stepper
                                v-model="item.count"
                                @change="onCountChanged(item)"
                                integer
                                v-if="item.goods_num"
                                :max="item.goods_num"
                            />

                            <span v-else style="margin-right: 20px"
                            >该商品暂时无货</span
                            >
                            <van-button
                                text="删除"
                                size="small"
                                @click.prevent="onClickDeleteCartItem(item.id)"
                            />
                        </van-col>
                    </van-row>
                </van-col>
            </van-row>


            <!-- 商品结算区域 -->
            <van-cell title="商品结算" value="总计不含运费">
                <template #label>
                    <p>
                        已勾选商品<span class="red">{{ getCheckedCount }}</span>
                        件，总价
                        <span class="red">¥{{ getCheckedAmount }}</span>
                    </p>
                </template>
            </van-cell>

            <!-- 结算按钮 -->
            <van-button type="primary" size="large" @click="onClickCreateOrder"
            >去结算</van-button
            >
        </div>
        <div v-else>
            <van-empty description="请先添加商品到购物车"></van-empty>
        </div>

    </div>
</template>

<script>
import {
    getCartList,
    updateCartCount,
    updateCartChecked,
    deleteCartItem,
} from "@/api/cart.js";


export default {
    components: {

    },
    data() {
        return {
            cartList: [],
        };
    },
    computed: {
        getCheckedCount() {
            let sum = 0;
            this.cartList.forEach((item) => {
                if (item.is_checked) sum += 1;
            });
            return sum;
        },
        getCheckedAmount() {
            let amount = 0;
            this.cartList.forEach((item) => {
                if (item.is_checked) amount += item.price * item.count;
            });
            return amount;
        },
    },
    created() {
        this.getCartList();
    },
    methods: {
        async getCartList() {
            try {
                let result = await getCartList();
                if (result.code == 1) {
                    this.cartList = result.data;
                    if(result.data.length==0){

                        console.log("购物车为空")
                    }else{
                        this.cartList.forEach((item) => {
                            if (item.goods_num == 0) {
                                //如果商品库存数为0，则不能选中
                                item.is_checked = false;
                                this.onCheckedChange(item.id, item.is_checked);
                            }
                        });
                    }
                } else if (result.code == 2) {
                    //需要用户登录的
                    this.$router.push({name:"welcome"});
                } else {
                    throw result.msg;
                }
            } catch (error) {
                console.log({ title: "错误", message: error });
            }
        }, //===================================================
        async onCountChanged(item) {
            let params = { id: item.id, count: item.count };

            //请求后端更改数据-购物商品数量
            try {
                let result = await updateCartCount(params);
                //console.log(result);
                if (result.code == 1) {
                    this.getCartList(); //重新加载购物车列表
                } else {
                    throw result.msg;
                }
            } catch (error) {
                this.$dialog.alert({ title: "错误", message: error });
            }
        }, //===================================================
        async onCheckedChange(item) {
            let id = item.id;
            let is_checked = item.is_checked == true ? 1 : 0;

            let params = { id, is_checked };
            // console.log(params)
            //请求后端更改数据-购物商品选中状态
            try {
                let result = await updateCartChecked(params);
                if (result.code == 1) {
                    this.getCartList(); //重新加载购物车列表
                } else {
                    throw result.msg;
                }
            } catch (error) {
                this.$dialog.alert({ title: "错误", message: error });
            }
        }, //===================================================
        async onClickDeleteCartItem(id) {
            //请求后端更改数据-删除购物商品
            let ids = id;
            try {
                let result = await deleteCartItem({ ids });
                if (result.code == 1) {
                    this.getCartList();
                } //重新加载购物车列表
                else {
                    throw result.msg;
                }
            } catch (error) {
                this.$dialog.alert({ title: "错误", message: error });
            }
        }, //===================================================
        onClickCreateOrder() {
            if (this.cartList.length === 0) {
                this.$toast("您的购物车为空");
                return;
            }
            //要确保购物车数据和后端数据库的是一致的 .....
            this.$router.push({ name: "order_create" });
        },
    },
};
</script>

<style lang="less" scoped>
.shopcart-container{
    padding: 0px 10px;
}
.info {
    padding: 0px 10px;
    font-size: 13px;
    font-weight: bold;
}
.price {
  text-align: left;
  font-size: 16px;
  font-weight: bold;
  color: red;
  display: flex;
  align-items: center;
}

.opration {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.red {
    color: red;
    font-weight: bold;
    font-size: 16px;
}
</style>
